package org.goldfish.asyncdemo;

import jakarta.servlet.AsyncContext;
import jakarta.servlet.AsyncEvent;
import jakarta.servlet.AsyncListener;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "helloServlet", value = "/hello-servlet", asyncSupported = true)
public class HelloServlet extends HttpServlet {
    private String message;

    public void init() {
        message = "Hello from Goldfish!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AsyncContext asyncContext = request.startAsync();
        asyncContext.addListener(new MyAsyncListener());
        asyncContext.start(() ->
        {
            try {
                Thread.sleep(5000);
                PrintWriter out = asyncContext.getResponse().getWriter();
                out.println("<html><body>");
                out.println("<h1>" + message + "</h1>");
                out.println("</body></html>");
                asyncContext.complete();
            } catch (InterruptedException | IOException e) {
                e.printStackTrace();
            }
        });

//        response.setContentType("text/html");
//
//        // Hello
//        PrintWriter out = response.getWriter();
//        out.println("<html><body>");
//        out.println("<h1>" + message + "</h1>");
//        out.println("</body></html>");
    }

    public void destroy() {
    }

    class MyAsyncListener implements AsyncListener {
        public void onComplete(AsyncEvent event) throws IOException {
            System.out.println("Complete");
        }

        public void onTimeout(AsyncEvent event) throws IOException {
            System.out.println("Timeout");
        }

        public void onError(AsyncEvent event) throws IOException {
            System.out.println("Error");
        }

        public void onStartAsync(AsyncEvent event) throws IOException {
            System.out.println("Start Async");
        }
    }
}